package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.ViewDao;
import model.View;
import util.GetWord;

/**
 * Servlet implementation class AddViewServlet
 */
@WebServlet("/AddViewServlet")
public class AddViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddViewServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		String vname = "";
		String info = "";
		String price = "0";
		String savePath = this.getServletContext().getRealPath("/upload");
		File file = new File(savePath);
		if (!file.exists() && !file.isDirectory()) {
		//	System.out.println(savePath + "1234");
			file.mkdir();
		}
		String message = "";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			if (!ServletFileUpload.isMultipartContent(request)) {
				return;
			}
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString("UTF-8");
				//	System.out.println(name + "=" + value);
					if (name.equals("vname")) {
						vname = value;
					} else if (name.equals("info")) {
						info = value;
					} else if (name.equals("price")) {
						price = value;
					}
				} else {

					String filename = item.getName();
				//	System.out.println(filename);
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					filename = filename.substring(filename.lastIndexOf("\\") + 1);
					String word = GetWord.getPingYin(vname);
					filename = word + ".jpg";
					InputStream in = item.getInputStream();
					FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
					byte buffer[] = new byte[1024];
					int len = 0;
					while ((len = in.read(buffer)) > 0) {
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
					item.delete();
					if (price != null) {
						if (!ViewDao.getViewNoCacheForBool(word)) {
							View view = new View();
							view.setName(word);
							view.setVcname(vname);
							view.setInfo(info);
							int priceToInt = Integer.parseInt(price);
							view.setPrice(priceToInt);
							view.setLocation("upload/" + word + ".jpg");
							ViewDao.addView(view);
							if (ViewDao.getViewNoCacheForBool(word)) {
								
								String cp = "http://" + request.getServerName() + ":" + request.getServerPort()
										+ request.getContextPath();
							//	System.out.println(cp);
								
								URL url = new URL(cp + "/upload/template.html");
								String imagePath = cp + "/"+view.getLocation();
								String disrPath = this.getServletContext().getRealPath("/upload");
								String fileName = view.getName();
							//	System.out.println("imagePath = " + imagePath);
							//	System.out.println("disrPath = "+disrPath);
							//	System.out.println("fileName = "+fileName);
							//	util.CreateHtmlUtils2.MakeHtml(url, imagePath, disrPath, fileName);
								
								String flag = "3";
								request.setAttribute("flag", flag);
								request.getRequestDispatcher("/admin/AdminViewList.jsp").forward(request, response);
							} else {
								String flag = "2";
								request.setAttribute("flag", flag);
								request.getRequestDispatcher("/admin/AdminViewList.jsp").forward(request, response);
							}

						} else {
							String flag = "2";
							request.setAttribute("flag", flag);
							request.getRequestDispatcher("/admin/AdminViewList.jsp").forward(request, response);
						}
					}
				}
			}
		} catch (Exception e) {
			String flag = "2";
			request.setAttribute("flag", flag);
			request.getRequestDispatcher("/admin/AdminViewList.jsp").forward(request, response);

		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
